import React, { useState, useEffect, useMemo } from 'react';
import {
  Table,
  Card,
  PaginationProps,
  Button,
  Space,
  Typography,
  Tag,
} from '@arco-design/web-react';
import type { TableColumnProps } from '@arco-design/web-react';
import PermissionWrapper from '@/components/PermissionWrapper';
import { IconDownload, IconPlus } from '@arco-design/web-react/icon';
import axios from 'axios';
import useLocale from '@/utils/useLocale';
import SearchForm from './form';
import locale from './locale';
import styles from './style/index.module.less';
import './mock';
import '../orgnize/mock';
import KeepAlive, { useActivate, useAliveController } from 'react-activation';
import { useHistory } from 'react-router-dom';
import { DetailModal } from './detailModal';
import * as Model from '@/services/model';
import Api from '@/services/api';
const { Title, Text } = Typography;
export const ContentType = ['图文', '横版短视频', '竖版短视频'];
export const FilterType = ['规则筛选', '人工'];
export const Status = ['已上线', '未上线'];

const generateTreeData = (data) => {
  let res = [data.name];

  if (data.children) {
    res = res.concat(generateTreeData(data.children));
  }

  return res;
};
function SearchTable() {
  const t = useLocale(locale);
  const history = useHistory();

  const [treeData, setTreeData] = useState([]);

  const [userDetail, setUserDetail] = useState<Model.User | false>(false);

  const columns: TableColumnProps[] = [
    { title: 'ID', dataIndex: 'id' },
    { title: '用户名', dataIndex: 'name' },
    {
      title: '是否超级管理员',
      dataIndex: 'administrator',
      render: (col) => {
        return col ? '是' : '否';
      },
    },
    {
      title: '角色',
      dataIndex: 'role',
    },

    {
      title: '部门',
      dataIndex: 'orgnize',
      render: (col) => {
        return (
          <Space direction="vertical">
            {col.map((e) => {
              return (
                <Text key={e.id} style={{ color: 'rgb(var(--primary-6))' }}>
                  {generateTreeData(e).join('-')}
                </Text>
              );
            })}
          </Space>
        );
      },
    },
    {
      title: '操作',
      render: (col, item) => {
        return (
          <Space>
            <Button
              type="primary"
              size="small"
              onClick={() => setUserDetail(item)}
            >
              编辑用户
            </Button>

            <Button
              type="primary"
              size="small"
              status="danger"
              onClick={() => setUserDetail(item)}
            >
              删除用户
            </Button>

            <Button
              type="default"
              size="small"
              status="danger"
              onClick={() => setUserDetail(item)}
            >
              重置密码
            </Button>
          </Space>
        );
      },
    },
  ];

  const [data, setData] = useState([]);
  const [pagination, setPatination] = useState<PaginationProps>({
    sizeCanChange: true,
    showTotal: true,
    pageSize: 10,
    current: 1,
    pageSizeChangeResetCurrent: true,
  });
  const [loading, setLoading] = useState(true);
  const [formParams, setFormParams] = useState({});
  const aliveController = useAliveController();
  useActivate(() => {
    console.log('active');
    fetchOrgnizeData();
  });
  useEffect(() => {
    fetchOrgnizeData();
  }, []);
  useEffect(() => {
    fetchData();
  }, [pagination.current, pagination.pageSize, JSON.stringify(formParams)]);

  const fetchOrgnizeData = async () => {
    setLoading(true);
    const res = await Api.orgnizeList({}).catch(() => {
      return false;
    });
    if (res) {
      setTreeData(generateTreeData(res.list));
    }
    setLoading(false);
  };

  function fetchData() {
    const { current, pageSize } = pagination;
    setLoading(true);
    axios
      .get('/api/users/list', {
        params: {
          page: current,
          pageSize,
          ...formParams,
        },
      })
      .then((res) => {
        console.log(res.data.list);
        setData(res.data.list);
        setPatination({
          ...pagination,
          current,
          pageSize,
          total: res.data.total,
        });
        setLoading(false);
      });
  }

  function onChangeTable({ current, pageSize }) {
    setPatination({
      ...pagination,
      current,
      pageSize,
    });
  }

  function handleSearch(params) {
    setPatination({ ...pagination, current: 1 });
    setFormParams(params);
  }

  return (
    <Card>
      <SearchForm onSearch={handleSearch} />
      <div className={styles['button-group']}>
        <Space>
          <Button
            onClick={() => setUserDetail(new Model.User())}
            type="primary"
            icon={<IconPlus />}
          >
            新增用户
          </Button>

          <Button type="default" icon={<IconDownload />}>
            导出用户
          </Button>
        </Space>
      </div>
      <Table
        rowKey="id"
        loading={loading}
        onChange={onChangeTable}
        pagination={pagination}
        columns={columns}
        data={data}
      />

      <DetailModal
        onCancel={() => setUserDetail(false)}
        onOk={() => setUserDetail(false)}
        userInfo={userDetail}
      />
    </Card>
  );
}

export default SearchTable;
